import 'package:flame/components.dart';
import 'package:flame/events.dart';
import 'package:flutter/material.dart';

class MyButton extends PositionComponent with TapCallbacks {
  final Function() onPressed;
  final String text;
  final double width;
  final double height;
  final Color backgroundColor;
  final Color borderColor;
  final double borderWidth;

  late TextComponent _textComponent;

  MyButton({
    required this.onPressed,
    required this.text,
    this.width = 50,
    this.height = 40,
    this.backgroundColor = const Color(0xFF2196F3),
    this.borderColor = const Color(0xFF1976D2),
    this.borderWidth = 2,
    super.position,
  }) : super(size: Vector2(width, height));

  @override
  void onLoad() {
    super.onLoad();

    // 添加背景
    add(
      RectangleComponent(size: size, paint: Paint()..color = backgroundColor),
    );

    // 添加边框效果
    add(
      RectangleComponent(
        size: Vector2(size.x - borderWidth * 2, size.y - borderWidth * 2),
        position: Vector2(borderWidth, borderWidth),
        paint: Paint()..color = const Color(0xFFFFFFFF),
      ),
    );

    // 添加文本
    _textComponent = TextComponent(
      text: text,
      textRenderer: TextPaint(
        style: TextStyle(
          color: borderColor,
          fontSize: 16,
          fontWeight: FontWeight.bold,
        ),
      ),
      anchor: Anchor.center,
      position: size / 2,
    );
    add(_textComponent);
  }

  @override
  void onTapDown(TapDownEvent event) {
    // 按钮按下效果
    _textComponent.position = size / 2 + Vector2(1, 1);
    super.onTapDown(event);
  }

  @override
  void onTapUp(TapUpEvent event) {
    // 恢复按钮位置
    _textComponent.position = size / 2;
    onPressed();
    super.onTapUp(event);
  }

  @override
  void onTapCancel(TapCancelEvent event) {
    // 恢复按钮位置
    _textComponent.position = size / 2;
    super.onTapCancel(event);

  }
  
  // 提供对文本组件的公共访问
  TextComponent get textComponent => _textComponent;
}